<template>
  <el-drawer v-model="visible" class="task-drawer">
    <div class="container flex-column">
      <el-steps :active="activeStep" align-center class="task-step">
        <el-step title="发布设置" @click="activeStep = 1" class="hover" />
        <el-step title="选择学生" />
        <el-step title="发布成功" />
      </el-steps>
      <main class="content">
        <TaskForm
          :task-type="initTaskInfo.task_type"
          :course="initTaskInfo.course"
          ref="taskForm"
          v-show="activeStep === 1"
        />
        <span v-if="activeStep === 2 && initTaskInfo.task_type === 3"
          >无需选择学生</span
        >
        <StudentSelectBox
          ref="studentSelectRef"
          v-else-if="activeStep === 2"
          v-model:classTypeList="selectList"
          v-model:activeTab="selectType"
          v-model:activeClassList="selectClassList"
          :select-class-info="initTaskInfo?.class_info || []"
        />
      </main>
      <footer class="flex-between drawer-footer">
        <el-button class="btn" @click="visible = false">取消</el-button>
        <div class="drawer-right flex">
          <template v-if="activeStep === 1">
            <div class="confirm-btn flex-center hover" @click="onNext">
              下一步
            </div>
          </template>
          <template v-else>
            <div class="desc" v-if="initTaskInfo.task_type !== 3">
              已选：{{
                selectType === '1'
                  ? `${selectClassList.length}个班级`
                  : `${studentSelectRef?.getCheckedStudentList().length}个学生`
              }}
            </div>
            <el-button
              class="btn"
              @click="onPublish(0)"
              v-if="initTaskInfo.task_type !== 3"
              >存草稿</el-button
            >
            <el-button type="primary" @click="onPublish(1)">发布</el-button>
          </template>
        </div>
      </footer>
    </div>
  </el-drawer>
</template>

<script setup>
import { defineModel, ref } from 'vue'
import { useTaskStore, useAuthStore } from '@/stores'
import { storeToRefs } from 'pinia'
import { useRoute } from 'vue-router'
import {
  postPracticeTask,
  postCollect,
  getPendingTaskOfDetail,
  postUseQuestionList
} from '@/apis/assignment/index'

import TaskForm from './TaskForm.vue'
import StudentSelectBox from './StudentSelectBox.vue'
import router from '@/router'
import { ElMessage } from 'element-plus'

const visible = defineModel('visible')
const authStore = useAuthStore()
const { nowGlobalStageId } = storeToRefs(authStore)

const props = defineProps({
  taskId: {
    type: Number,
    required: false
  }, // 编辑任务传任务id
  taskType: {
    type: Number // 1-课程 2-习题  3-举一反三 4-错题
  },
  course: {
    required: false,
    type: Object,
    default: () => {
      return { course_id: null, course_name: '', subjectId: 0, chapterList: [] }
    }
  },
  // 举一反三业务
  oneList: {
    default: [] // 题目列表
  },
  classSelect: {
    type: Object
  },
  studentList: {
    default: []
  },
  sourceTaskId: {
    // 原任务id
    type: Number,
    required: false
  }
})

const initTaskInfo = ref({
  task_type: props.taskType,
  course: props.course
})

const route = useRoute()
const useTask = useTaskStore()
const taskStore = storeToRefs(useTask)

const activeStep = ref(1)
const taskForm = ref()
const taskFormParam = ref({})

const studentSelectRef = ref()
const selectList = ref([]) // 班级树状结构
const selectClassList = ref([])
const selectType = ref('1')

const onNext = async () => {
  let formParam = await taskForm.value.getForm()
  if (!formParam) return

  let { course_id, subjectId, chapterList } = initTaskInfo.value.course
  switch (initTaskInfo.value.task_type) {
    case 1:
      formParam = {
        ...formParam,
        subject_id: subjectId,
        course_id: Number(course_id),
        chapter_id: chapterList
      }
      break
    case 2:
      formParam = {
        ...formParam,
        question: props.taskId
          ? initTaskInfo.value.question
          : taskStore.taskList.value.map(question => ({
              question_id: question.topic_id,
              question_type: question.topic_type,
              source: question.source,
              relation_id: question.relation_id || 0,
              set_total_score: question.totalScore,
              score_strategy: question.score_strategy,
              ...(question.subScore && {
                children_question:
                  question.subScore.map(child_question => ({
                    question_id: child_question.id,
                    score_strategy: child_question.score_strategy || 0,
                    set_total_score: child_question.score
                  })) || []
              })
            }))
      }
      console.log('题目', taskStore.taskList.value)
      break
    case 3:
      formParam = {
        ...formParam,
        relation_task_id: props.sourceTaskId,
        question: props.oneList.map(question => ({
          question_id: question.topic_id,
          question_type: question.topic_type,
          source: question.source,
          relation_id: question.relation_id || 0
        }))
      }
      break
  }
  taskFormParam.value = formParam
  activeStep.value++
}

/**
 *
 * @param {*} type 0-存草稿 1-发布
 */
const onPublish = type => {
  if (initTaskInfo.value.task_type !== 3) {
    if (selectType.value === '1' && selectClassList.value.length === 0) {
      ElMessage.error('请选择班级')
      return
    }
    if (
      selectType.value === '2' &&
      !studentSelectRef.value.getCheckedStudentList().length
    ) {
      ElMessage.error('请选择学生')
      return
    }
  }
  if (initTaskInfo.value.task_type === 1) {
    postCourseTaskInfo(type)
  } else if (
    initTaskInfo.value.task_type === 2 ||
    initTaskInfo.value.task_type === 3
  ) {
    postPracticeTaskInfo(type)
  }
}

// 选择的班级/学生转换成参数结构
const getTaskClassParam = () => {
  function getStudentList(layerList) {
    let studentIds = []
    layerList.forEach(layer => {
      let ids = layer
        .filter(student => student.checked)
        .map(student => student.student_id)
      studentIds.push(...ids)
    })
    return studentIds
  }

  let resList = []
  selectList.value.forEach(typeClass => {
    typeClass.classList.forEach(classItem => {
      if (selectType.value === '1') {
        if (selectClassList.value.indexOf(classItem.value) >= 0) {
          resList.push({
            class_id: Number(classItem.value),
            class_name: classItem.label,
            class_type: classItem.class_type,
            student_ids: []
          })
        }
      } else {
        let student_ids = getStudentList(classItem.layerList)
        if (student_ids.length) {
          let resItem = {
            class_id: Number(classItem.value),
            class_name: classItem.label,
            class_type: classItem.class_type,
            student_ids
          }
          resList.push(resItem)
        }
      }
    })
  })
  return resList
}

/**
 * 发布习题任务/举一反三任务
 * @param {*} type 0-存草稿 1-发布
 */
const postPracticeTaskInfo = async type => {
  let class_info = []
  if (props.taskType === 3) {
    class_info = [
      {
        class_id: props.classSelect.value,
        class_name: props.classSelect.name,
        class_type: props.classSelect.class_type,
        student_ids: props.studentList.map(student =>
          String(student.student_id)
        )
      }
    ]
  } else {
    class_info = getTaskClassParam()
  }
  let param = {
    ...taskFormParam.value,
    release: type,
    task_classification: route.path.includes('target-boost') ? 2 : 1,
    subject_id: initTaskInfo.value?.task_id
      ? initTaskInfo.value?.subject_id
      : authStore.nowGlobalSubjectId,
    class_info,
    stage: nowGlobalStageId.value
  }
  if (initTaskInfo.value?.task_id) {
    param.task_id = initTaskInfo.value?.task_id
  }
  const res = await postPracticeTask(param)
  console.log('任务发布结果', res, param)
  if (res.code === 1) {
    visible.value = false
    // 数据埋点
    postCollect({
      action_type: 2,
      task_id: res.data.task
    })
    // 发布习题提交题目引用次数
    if (type === 1) {
      postUseQuestionList({
        question_id: param.question.map(item => item.question_id)
      })
    }

    if (!props.taskId) {
      useTask.reset()
    }
    if (param.release === 1) {
      ElMessage.success('任务发布成功!')
    } else {
      ElMessage.success('任务保存成功!')
    }
    router.replace({
      name: 'assignment',
      query: {
        type: param.release
      }
    })
  }
}

/**
 * 发布课程任务
 * @param {*} type 0-存草稿 1-发布
 */
const postCourseTaskInfo = async type => {
  let class_info = getTaskClassParam()
  let param = {
    ...taskFormParam.value,
    release: type,
    class_info,
    stage: nowGlobalStageId.value
  }
  if (initTaskInfo.value?.task_id) {
    param.task_id = initTaskInfo.value?.task_id
  }
  const res = await postPracticeTask(param)
  if (res.code === 1) {
    visible.value = false
    postCollect({
      action_type: 2,
      task_id: res.data.task_id
    })

    if (param.release === 1) {
      ElMessage.success('任务发布成功!')
    } else {
      ElMessage.success('任务保存成功!')
    }
    router.replace({
      name: 'assignment',
      query: {
        type
      }
    })
  }
}

// 获取待发布任务的参数
const getPendingTaskOfDetailInfo = async () => {
  const res = await getPendingTaskOfDetail({
    task_id: props.taskId
  })
  const { task_info } = res.data
  if (task_info.task_type === 1) {
    initTaskInfo.value.course = {
      course_id: task_info.course_id,
      course_name: '',
      subjectId: task_info.subject_id,
      chapterList: task_info.chapter_id
    }
  }
  initTaskInfo.value = {
    ...initTaskInfo.value,
    ...task_info
  }
  taskForm.value.initForm(res.data.task_info)
}

const initData = () => {
  if (props.taskId) {
    getPendingTaskOfDetailInfo()
  }
}

initData()
</script>

<style lang="less" scoped>
.container {
  gap: 10px;
  height: 100%;
  font-size: @size-big;
  .task-step {
    :deep(.el-step) {
      .el-step__title.is-process {
        font-weight: normal;
      }
      .el-step__icon {
        width: 34px;
        height: 34px;
        background-color: #f5f6ff;
        border-color: #f5f6ff;
        color: #7382ef;
        .el-step__icon-inner {
          font-weight: normal;
          font-size: 16px;
        }
      }
      .is-finish {
        .el-step__icon {
          color: #fff;
          background-color: #7382ef;
          border-color: #7382ef;
        }
        .el-step__line {
          height: 6px !important;
          border-width: 6px !important;
          background-color: #7382ef;
          border-color: #7382ef;
        }
      }
    }
  }
  .drawer-footer {
    .desc {
      margin-right: 20px;
    }
    .btn {
      border-color: #7382ef;
      color: #7382ef;
    }
  }
  .content {
    flex: 1;
    overflow: auto;
  }
}
</style>

<!-- eslint-disable -->
<style lang="less">
.task-drawer {
  width: 620px !important;
  .el-drawer__header {
    margin-bottom: unset !important;
  }
  .el-drawer__body {
    padding-top: 0px;
  }
}
</style>
